package ltd.followkba.task;

import com.kcbsdk.ABean;
import com.kcbsdk.AFetchType;
import com.kcbsdk.AFileBase;
import com.kcbsdk.ARoomType;
import com.kcbsdk.AUserBase;
import com.kcbsdk.MyManage.ARelationsType;
import com.kcbsdk.MyManage.AUserFileType;
import com.kcbsdk.MyManage.AUserInfo;
import com.kcbsdk.MyManage.AVarType;
import com.kcbsdk.MyTools.ASmartDateType;
import com.kcbsdk.MyWorks.AAccountType;
import com.kcbsdk.MyWorks.ACommentInfo;
import com.kcbsdk.MyWorks.AFileInfo;
import com.kcbsdk.MyWorks.AFileType;
import com.kcbsdk.MyWorks.AShareSubType;
import com.kcbsdk.MyWorks.AShareType;
import com.kcbsdk.MyWorks.AUserRelationType;
import com.kcbsdk.MyWorks.AUserSearchType;
import com.kcbsdk.MyWorks.AWorksType;
import com.kcbsdk.wpapper;

import java.nio.ByteBuffer;
import java.util.Calendar;
import java.util.List;

import ltd.advskin.MRAM;
import ltd.advskin.utils.SubUtils;
import main.CApiUtils;
import main.MAPI;

import static com.kcbsdk.wpapper.*;
import static ltd.advskin.MSKIN.MLOGE;
import static ltd.advskin.MSKIN.MSTRING;
import static main.MAPI.MSLEEP;
import static main.MAPI.mMyManage;
import static main.MAPI.mMyTools;
import static main.MAPI.mMyUtils;
import static main.MAPI.mMyWorks;

public class App32 {
    private static byte gWorksType;
    private static int gUserID;
    private static String gLoginFlag;
    private static boolean IsPause;
    private static String gLastError;

    public static void MLOG(String text) {
        MSTRING("App32 " + text);
    }
    public static synchronized void setUser(BDbsAccount bDbsAccount){
        if (bDbsAccount != null) {
//MLOGE(String.format("QueueA gWorksTypeD %s %s", gWorksType, bDbsAccount.WorksType));
            setUser(bDbsAccount.LoginFlag, bDbsAccount.WorksType);
        }
    }
    public static synchronized void setUser(String loginFlag, byte worksType){
        gLastError = null;
        if (loginFlag != null){
            String[] split = loginFlag.split(":");
            if (split.length > 1) {
                gUserID = MAPI.STRING_DEC32(split[0]);
                gLoginFlag = split[1];
            }
        }
        gWorksType = worksType;
//MLOGE(String.format("QueueA gWorksTypeE %s", gWorksType));
    }
    public static synchronized void setPause(boolean pause){
        IsPause = pause;
        breakWaitting();
    }
    public static synchronized String getLastError(){
        return gLastError;
    }

    public static synchronized BAppUser getUserInfo(String userIdS){
        if (!MAPI.isEmpty(userIdS)) {
            AUserBase aUserBase = new AUserBase();
            aUserBase.UserID = MAPI.STRING_DEC32(userIdS);
            BAppUser bAppUser = new BAppUser();
            long tick = System.currentTimeMillis();
            while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
                ABean aBean = MAPI.mMyWorks.fetchUserDetail(aUserBase, null);
                if (MAPI.isEmpty(bAppUser.UserName)) {
                    bAppUser.UserName = mMyUtils.getNickName(aUserBase);
                }
                if (MAPI.isEmpty(bAppUser.Intro)) {
                    bAppUser.Intro = mMyUtils.getUserIntro(aUserBase);
                }
                if (bAppUser.UserName != null && bAppUser.Intro != null && aBean.ErrorStr == null) {
                    if (aBean.mObject instanceof AUserInfo) {
                        AUserInfo aUserInfo = (AUserInfo) aBean.mObject;
                        bAppUser.WorksType = gWorksType;
                        bAppUser.UserID = aUserBase.UserID;
                        bAppUser.UserIdS = userIdS;
                        bAppUser.Gender = aUserInfo.Gender;
                        bAppUser.HeadFile = mMyUtils.getUserFileName(AUserFileType.IMG_SMALL, aUserBase, MRAM.gsCachePath);
//MLOG(String.format("QueueA gWorksTypeE %s", gWorksType));
                        bAppUser.WorksQty = aUserInfo.WorksQty[gWorksType];
                        bAppUser.ListenQty = aUserInfo.ListenQty;
                        bAppUser.LikeQty = aUserInfo.LikeQty;
                        bAppUser.FansQty = aUserInfo.FansQty;
                        bAppUser.CareQty = aUserInfo.CareQty;
                        String fullCity = mMyUtils.getAreaFullCityName(aUserInfo.AreaCode);
                        String[] split = fullCity.split(" ");
                        if (split.length > 0) {
                            bAppUser.Province = split[0];
                            if (split.length > 1) {
                                bAppUser.City = split[1];
                            }
                        }
                        bAppUser.Birthday = mMyUtils.getSmartDate(ASmartDateType.SMART_BIRTHDAY, aUserInfo.Birthday); // 生日
//MLOG(String.format("QueueA getUserInfoE"));
                        return bAppUser;
                    }
                }
                sleepWaitting(100);
            }
        }
        return null;
    }


    public static synchronized String[] getWorksList(byte worksType, String userIdS, boolean getAll){
        if (changeUser()) {
//                MLOG(String.format("getWorksListA %s %s %s", aWorksType, userIdS, getAll));
            AUserBase aUserBase = new AUserBase();
            aUserBase.UserID = MAPI.STRING_DEC32(userIdS);
            long tick = System.currentTimeMillis();
            while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
                ABean aBean = mMyWorks.fetchWorksList(AFetchType.LIST_NORMAL, worksType, wpapper.TOOLS_WORKS_LIST_WORKS, aUserBase, null, 0);
                if (aBean.ErrorStr == null) {
                    int length = (aBean.mBean != null) ? aBean.mBean.size() : 0;
                    String[] strings = new String[length];
//                        MLOG(String.format("getWorksListA1 %s %s", aWorksType, length));
                    for (int index = 0; index < length; index++) {
                        AFileBase aFileBase = (AFileBase) aBean.mBean.get(index);
                        strings[index] = String.format("%s", aFileBase.FileID);
                    }
                    return strings;
                }
            }
        }
        return null;
    }
    public static synchronized BAppWorks getWorksInfo(String userIdS, String worksIdS){
        if (!MAPI.isEmpty(userIdS) && !MAPI.isEmpty(worksIdS)) {
            AFileBase aFileBase = new AFileBase();
            aFileBase.UserID = MAPI.STRING_DEC32(userIdS);
            aFileBase.FileID = MAPI.STRING_DEC32(worksIdS);
            BAppWorks bAppWorks = new BAppWorks();
            long tick = System.currentTimeMillis();
            while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
                ABean aBean = MAPI.mMyWorks.fetchFileDetail(aFileBase, null);
                if (MAPI.isEmpty(bAppWorks.WorksName)) {
                    bAppWorks.WorksName = mMyUtils.getFileName(aFileBase);
                }
                if (MAPI.isEmpty(bAppWorks.ArtistName)) {
                    bAppWorks.ArtistName = mMyUtils.getFileSubName(aFileBase);
                }
                if (MAPI.isEmpty(bAppWorks.Intro)) {
                    bAppWorks.Intro = mMyUtils.getFileIntro(aFileBase);
                }
                if (aBean.ErrorStr == null && bAppWorks.WorksName != null && bAppWorks.ArtistName != null && bAppWorks.Intro != null) {
                    if (aBean.mObject instanceof AFileInfo) {
                        AFileInfo aFileInfo = (AFileInfo) aBean.mObject;
                        bAppWorks.WorksType = aFileInfo.WorksType;
                        bAppWorks.UserID = aFileInfo.UserID;
                        bAppWorks.FileID = aFileInfo.FileID;
                        bAppWorks.MusicID0 = aFileInfo.MusicID0;
                        bAppWorks.MusicID1 = aFileInfo.MusicID1;
                        bAppWorks.ClassStyle = aFileInfo.ClassStyle;
                        bAppWorks.IsOriginal = ((aFileInfo.ClassStyle & (1 << KCB_LIST_ORIGINAL_FLAG)) != 0) ? true : false;
//                            bAppWorks.IsChorus = ((aFileInfo.ClassStyle & ((1<<KCB_LIST_CHORUS_FEMALE)|((1<<KCB_LIST_CHORUS_MALE)|((1<<KCB_LIST_CHORUS_NORMAL))) != 0) ? true : false;
//                        bAppWorks.HaveFile = aFileInfo.HaveFile;
//                            bAppWorks.FileID = aFileInfo.FileID;
                        bAppWorks.UserIdS = userIdS;
                        bAppWorks.WorksIdS = worksIdS;
                        bAppWorks.ReleaseDate = aFileInfo.ReleaseDate;
                        bAppWorks.CommentQty = aFileInfo.CommentQty;
                        bAppWorks.MoneyQty = aFileInfo.GiftQty;
                        bAppWorks.ShareQty = aFileInfo.ShareQty;
                        bAppWorks.ListenQty = aFileInfo.ListenQty;
                        bAppWorks.LikeQty = aFileInfo.LikeQty;
                        AFileType aFileType = bAppWorks.HavePhoto ? AFileType.FILE_COVER_PHOTO : AFileType.FILE_COVER_MPP;
                        bAppWorks.CoverFile = MAPI.mMyUtils.getWorksFileName(aFileType, aFileBase, MRAM.gsCachePath);
//
//                        AFileType aFileType = MAPI.mMyUtils.getPhotoFileType(bAppWorks);
//                        if (aFileType != null) {
//                            bAppWorks.CoverFile = MAPI.mMyUtils.getWorksFileName(aFileType, aFileBase, MRAM.gsCachePath);
//                        }
                        return bAppWorks;
                    }
                }
                sleepWaitting(100);
            }
        }
        return null;
    }
    public static synchronized BFileBase[] getRankList(byte worksType, AUserBase aUserBase, int maxQty){
        long tick = System.currentTimeMillis();
        int counter = 0;
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            if (counter == 0) {
                ABean aBean1 = MAPI.mMyWorks.fetchUserDetail(aUserBase, null);
                if (aBean1.ErrorStr == null){
                    counter = 1;
//                            MLOG(String.format("RankA A2 %s(%s)%s", aUserBase.UserID, aWorksType, aBean.ErrorStr));
                }
            }else if (counter == 1) {
                ABean aBean2 = mMyWorks.fetchWorksList(AFetchType.LIST_NORMAL, worksType, wpapper.TOOLS_WORKS_LIST_WORKS, aUserBase, null, 0);
                if (aBean2.ErrorStr == null){
                    int length = (aBean2.mBean!=null) ? aBean2.mBean.size() : 0;
                    if (length >= maxQty){
                        length = maxQty;
                    }else if (length < aBean2.BeanQty) {
                        ABean aBean3 = mMyWorks.fetchWorksList(AFetchType.LIST_MORE, worksType, wpapper.TOOLS_WORKS_LIST_WORKS, aUserBase, null, 0);
//                                MLOG(String.format("RankA A3 %s", aBean3.ErrorStr));
                        sleepWaitting(100);
                        continue;
                    }
                    if (length > 0) {
//                                MLOG(String.format("RankA A5 %s(%s)%s/%s(%s)", aUserBase.UserID, aWorksType, length, aBean2.BeanQty, mMyUtils.getSmartDate(aBean2.NextTime)));
                        BFileBase[] bFileBases = new BFileBase[length];
                        for (int index = 0; index < length; index++) {
                            Object object = aBean2.mBean.get(index);
//                                            MLOG(String.format("RankA AAB %s %s %s", index, (aBean.mBean!=null) ? aBean.mBean.size() : 0, object));
                            if (object instanceof AFileBase) {
                                AFileBase aFileBase = (AFileBase) object;
                                bFileBases[index] = new BFileBase();
                                bFileBases[index].UserID = aFileBase.UserID;
                                bFileBases[index].FileID = aFileBase.FileID;
                                bFileBases[index].UserIdS = String.format("%s", aFileBase.UserID);
                                bFileBases[index].WorksIdS = String.format("%s", aFileBase.FileID);
                            }
                        }
                        return bFileBases;
                    }
                }
            }
            sleepWaitting(100);
        }
        return null;
    }


    public static synchronized BCommentInfo[] getCommentList(String userIdS, String worksIdS, String commentID, int maxQty){
        AFileBase aFileBase = new AFileBase();
        aFileBase.UserID = MAPI.STRING_DEC32(userIdS);
        aFileBase.FileID = MAPI.STRING_DEC32(worksIdS);

        long tick = System.currentTimeMillis();
        int length = 0;
        int commendID = MAPI.STRING_DEC32(commentID);
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            ABean aBean = mMyWorks.fetchListWorksFile(AFetchType.LIST_NORMAL, AFileType.FILE_COMMENT, aFileBase, commendID, null, 0);
            if (aBean.ErrorStr == null) {
                length = aBean.mBean != null ? aBean.mBean.size() : 0;
                if (length != aBean.BeanQty) {
                    if (length < maxQty && aBean.BeanQty < maxQty) {
                        ABean aBean1 = mMyWorks.fetchListWorksFile(AFetchType.LIST_MORE, AFileType.FILE_COMMENT, aFileBase, commendID, null, 0);
//                               MLOG(String.format("RunE E 继续读取 %s(%s)%s(%s)%s", length, aBean.BeanQty, maxQty, aBean1.ErrorStr, aBean1.mBean != null ? aBean1.mBean.size() : 0));
                        sleepWaitting(100);
                        continue;
                    }
                }
                if (length > 0) {
                    BCommentInfo[] bCommentInfos = new BCommentInfo[length];
                    for (int index = 0; index < length; index++) {
                        Object object = aBean.mBean.get(index);
                        if (object instanceof ACommentInfo) {
                            ACommentInfo aCommentInfo = (ACommentInfo) object;
                            bCommentInfos[index] = new BCommentInfo();
                            bCommentInfos[index].UserID = aCommentInfo.UserID;
                            bCommentInfos[index].FileID = aCommentInfo.FileID;
                            bCommentInfos[index].CommentID = aCommentInfo.CommentID;
                            bCommentInfos[index].UserIdS = String.format("%s", aCommentInfo.UserID);
                            bCommentInfos[index].WorksIdS = String.format("%s", aCommentInfo.FileID);
                            bCommentInfos[index].CommentIdS = String.format("%s", aCommentInfo.CommentID);
                            bCommentInfos[index].CommenterIdS = String.format("%s", aCommentInfo.mCommenter.UserID);
                            bCommentInfos[index].ReplyerIdS = String.format("%s", aCommentInfo.mReplyer.UserID);
//                                    MLOG(String.format("CommentA UserIdS %s %s %04x %04x", index, bCommentInfos[index].UserIdS, bCommentInfos[index].FileID, aCommentInfo.CommentID));
//                                    addBFileBase(bFileBase, lists);
                        } else {
                            MLOGE(String.format("CommentA ACommentInfo %s %s", length, aBean.BeanQty));
                        }
                    }
                    MLOG(String.format("CommentA lists.size %s_%04x_%s(%s/%s)", aFileBase.UserID, aFileBase.FileID, bCommentInfos.length, length, aBean.BeanQty));
                    return bCommentInfos;
                }
                return null;
            }
        }

        return null;
    }

    public static synchronized String setComment(String userID, String worksID, String commentID, String text){
        ACommentInfo aCommentInfo = new ACommentInfo();
        aCommentInfo.UserID = MAPI.STRING_DEC32(userID);
        aCommentInfo.FileID = MAPI.STRING_DEC32(worksID);
        aCommentInfo.CommentID = MAPI.STRING_DEC32(commentID);

//        MLOG("setCommentA1 ");
        if (changeUser()) {
//            MLOG("setCommentA1 " + mMyUtils.getCurrentLoginUserID());
            clearMyWorks();
            MLOG(String.format("setCommentA2 %s %s %04x %04x %s", gUserID, aCommentInfo.UserID, aCommentInfo.FileID, aCommentInfo.CommentID, text));
            mMyWorks.setComment(aCommentInfo, text);
            return waitMyWorksDone(0);              // isSuccessOperationWorks
        }

        return null;
    }
    public static synchronized String addLikeComment(String userIdS, String worksIdS, int[] commentID){
//        MLOG(String.format("RunE E addLikeComment %s(%s)%s", userIdS, worksIdS, commentID!=null?commentID.length:0));
        return addTypeWorks(userIdS, worksIdS, 4, 0, commentID);
    }
    public static synchronized String addLikeWorks(String userIdS, String worksIdS, int qty){
        return addTypeWorks(userIdS, worksIdS, 0, qty, null);
    }
    public static synchronized String addDownloadWorks(String userIdS, String worksIdS, int qty){
        return addTypeWorks(userIdS, worksIdS, 1, qty, null);
    }
    public static synchronized String addListenWorks(String userIdS, String worksIdS, int qty){
        return addTypeWorks(userIdS, worksIdS, 2, qty, null);
    }
    public static synchronized String addShareWorks(String userIdS, String worksIdS){
        return addTypeWorks(userIdS, worksIdS, 3, 1, null);
    }
    public static synchronized String addCollectWorks(String userIdS, String worksIdS){
        return addTypeWorks(userIdS, worksIdS, 5, 1, null);
    }

    private static synchronized String addTypeWorks(String userIdS, String worksIdS, int type, int qty, int[] commentID){
        AFileBase aFileBase = new AFileBase();
        aFileBase.UserID = MAPI.STRING_DEC32(userIdS);
        aFileBase.FileID = MAPI.STRING_DEC32(worksIdS);

        if (changeUser()) {
            clearMyWorks();
//                    MLOG(String.format("addTypeWorksA %s点赞%s_%04x(%s)%s", mMyUtils.getCurrentLoginUserID(), aFileBase.UserID, aFileBase.FileID, type, qty));
//                    MLOG(String.format("RunE E addLikeComment type:%s %s(%s)%s", type, userIdS, worksIdS, commentID!=null?commentID.length:0));
            switch (type) {
                case 0:
                    if (qty < 2) {                          // 点赞作品加1
                        mMyWorks.setLike(aFileBase, true);
                    }else {
                        commentID = new int[2];                 // 点赞作品加更多
                        commentID[0] = qty;
                        commentID[1] = 0;
                        mMyWorks.operationWorks(KCB_OPERATION_SET_LIKE, aFileBase, 0, null, commentID);
                    }
                    break;
                case 1:
                    mMyWorks.setDownload(aFileBase, qty);
                    break;
                case 2:
                    mMyWorks.setListen(aFileBase, qty);
                    break;
                case 3:
                    mMyWorks.setShare(aFileBase, AShareSubType.SHARE_WORK, null);
                    break;
                case 4:                                     // 点赞作品评论
                    if (commentID != null) {
                        mMyWorks.operationWorks(KCB_OPERATION_SET_LIKE, aFileBase, 0, null, commentID);
                    }
                    break;
                case 5:                                     // 收藏作品评论
                    mMyWorks.operationWorks(KCB_OPERATION_SET_COLLECT, aFileBase, qty, null, null);
                    break;
            }
            String result = waitMyWorksDone(0);
//                    MLOG(String.format("RunE E addTypeWorksA %s(%s)%s", type, result, commentID!=null?commentID.length:0));
            return result;
        }

        return null;
    }
    public static synchronized String deleteWorks(String userID, String worksID){
        return null;
    }


    public static synchronized String sendGifts(String userIdS, String worksIdS, int giftID, int amount, TaskEach taskEach){             // 送出礼物
        int userID = MAPI.STRING_DEC32(userIdS);
        int fileID = MAPI.STRING_DEC32(worksIdS);

        if (changeUser()) {
            String result;
            if (amount > 0) {
                clearMyWorks();
//                mMyWorks.sendGift(userID, fileID, giftID, amount);
                result = waitMyWorksDone(1);        // isSuccessSendGift
                MLOG(String.format("giftA Aw %s_%04x %s", userID, fileID, result));
            } else {
                result = "ok";
            }
            if ("ok".equals(result)) {
                clearMyManage();
//                mMyManage.operationMoney(KCB_OPERATION_MONEY_GET_GIFT_MONEY, 0, 0, "", "", "");
////                        MLOG(String.format("giftA B"));
//                if ("ok".equals(waitMyManageDone(1))) {
//                    taskEach.gGiftMoney = new int[5];        // 读取礼物的4个参数 已送免费礼物/免费礼物上限/已使用积分/剩余积分/判断时间是否是另一天
//                    Calendar calendar = Calendar.getInstance();
//                    taskEach.gGiftMoney[4] = calendar.get(Calendar.DAY_OF_MONTH);    // 判断时间是否是另一天
//                    String[] gpLocal_2 = mMyUtils.getGiftMoney().split(","); // 读取礼物的4个参数 已送免费礼物/免费礼物上限/已使用积分/剩余积分
////                            MLOG(String.format("giftA C %s", gpLocal_2.length));
//                    if (gpLocal_2.length >= 4) {
//                        for (int countG = 0; countG < 4; countG++) {  // MRAM.gGiftMoney[0]已送免费礼物 MRAM.gGiftMoney[1]免费礼物上限 MRAM.gGiftMoney[2]已使用积分 MRAM.gGiftMoney[3]剩余积分
//                            taskEach.gGiftMoney[countG] = MAPI.STRING_DEC32(gpLocal_2[countG]);
////                                    MLOG(String.format("giftA D %s %s", countG, bRunRam.gGiftMoney[countG]));
//                        }
//                    }
//                }
                return "ok";
            }
        }

        return null;
    }
    public static synchronized String addCareUser(String userID){

        AUserBase aUserBase = new AUserBase();
        aUserBase.UserID = MAPI.STRING_DEC32(userID);

        if (changeUser()) {
            clearMyManage();
            MLOG(String.format("addCareUser %s %s", mMyUtils.getCurrentLoginUserID(), aUserBase.UserID));
            mMyManage.setUserRelations(aUserBase, ARelationsType.USER_CARE, true);
            return waitMyManageDone(0);
        }

        return null;
    }


    private static synchronized void addBFileBase(BFileBase bFileBase, List<BFileBase> lists){
        int length = lists.size();
        for (int index = 0; index < length; index++) {
            if (bFileBase.UserIdS.equals(lists.get(index).UserIdS) && bFileBase.WorksIdS.equals(lists.get(index).WorksIdS)){
                return;
            }
        }
        lists.add(bFileBase);
    }
    public static synchronized List<BFileBase> getRankListB(String city){

        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            sleepWaitting(100);
        }

        return null;
    }

    public static synchronized String getAuthCode() {
        clearMyManage();
        mMyManage.fetchAuthCode();
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            int methodType = mMyManage.mSvrManage.getMethodType();
//MLOG(String.format("getAuthCodeA A %08x", methodType));
            if (mMyManage.isSuccessFetchAuthCode(methodType)) {
                String message = mMyManage.mSvrManage.getMethodMessage(methodType);
                MLOG(String.format("getAuthCodeA B %08x %s %sms %s %s", methodType, message, System.currentTimeMillis() - tick, MAPI.GET_FILE_LENGTH(mMyManage.mSvrManage.eventAuthCode()), mMyManage.mSvrManage.eventAuthCode()));
                return mMyManage.mSvrManage.eventAuthCode();
            }
            sleepWaitting(100);
        }
        MLOGE(String.format("getAuthCodeA C %s %s", IsPause, System.currentTimeMillis() - tick));
        return null;
    }
    public static synchronized String loginSvr(String account, String password, String authCode, BDbsAccount bDbsAccount){

        MLOG(String.format("AccountNameAA1"));
        clearMyManage();
        MLOG(String.format("AccountNameAA2"));
        String seret;
        if (!MAPI.isEmpty(password) && password.length() != 18) {
            seret = mMyUtils.makeSeretPassword(password);
        } else {
            seret = password;
        }
        MLOG(String.format("AccountNameAA3"));
        mMyManage.loginSvr(account, seret, authCode);
        long tick = System.currentTimeMillis();
        MLOG(String.format("AccountNameAB1"));
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            int methodType = mMyManage.mSvrManage.getMethodType();
            if (methodType != 0) {
                MLOG(String.format("AccountNameAB2 %08x %s %s %s", methodType, account, seret, authCode));
            }
            if (mMyManage.isSuccessLoginSvr(methodType)) {
                String message = mMyManage.mSvrManage.getMethodMessage(methodType);
                MLOG(String.format("AccountNameABA2 %08x %s", methodType, message));
                if (message != null) {
                    bDbsAccount.Status = message;
                    if ("ok".equals(message)) {
                        bDbsAccount.UserID = mMyManage.mSvrManage.g4OwnUserID;
                        bDbsAccount.UserIdS = String.format("%s", bDbsAccount.UserID);
                        bDbsAccount.LoginFlag = String.format("%s:%s", bDbsAccount.UserIdS, mMyManage.getLoginFlag());
                        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
                            bDbsAccount.UserName = mMyUtils.getNickName(bDbsAccount);
                            if (bDbsAccount.UserName != null) {
                                break;
                            }
                        }
                        MLOG(String.format("AccountNameABA3 %s %s", bDbsAccount.UserID, bDbsAccount.LoginFlag));
                    } else {
                        MLOGE(String.format("AccountNameABa %08x %s %s %s", methodType, message, bDbsAccount.UserID, bDbsAccount.LoginFlag));
                    }
                    return message;
                }
            }
            sleepWaitting(100);
        }
        MLOG(String.format("AccountNameAB44"));

        return "超时";
    }

    public static synchronized String downloadHeadFile(BAppUser bAppUser){
        return downloadHeadFile(AUserFileType.IMG_SMALL, bAppUser, false);
    }
    public static synchronized String downloadHeadFile(AUserFileType aUserFileType, BAppUser bAppUser, boolean ignoreDone){       // 跳过ignoreDone检查
        AFileBase aFileBase = new AFileBase();
        aFileBase.UserID = MAPI.STRING_DEC32(bAppUser.UserIdS);
        aFileBase.FileID = aUserFileType.getType();
        String fileName = mMyUtils.getUserFileName(aUserFileType, aFileBase, MRAM.gsCachePath);
        if (ignoreDone){                                        // 需要强制更新
            MAPI.DELETE_FILE(fileName);                         // 删除原来的文件
            MAPI.DEL_FILE_DONE(fileName);
//            MLOG(String.format("UserInfoA ignoreDone A %s %s %s", aUserFileType, MAPI.GET_FILE_LENGTH(fileName), fileName));
        }
        if (!MAPI.IS_FILE_DONE(fileName)) {
//            MLOG(String.format("UserInfoA ignoreDone B %s %s %s", aUserFileType, MAPI.GET_FILE_LENGTH(fileName), fileName));
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(128);
            String result = mMyUtils.threadDownloadFiles(ARoomType.ROOM_USER.getType(), aFileBase.UserID, aFileBase.FileID, 0, 0, null, fileName, byteBuffer);
            if ("ok".equals(result)) {
//                MLOG(String.format("UserInfoA ignoreDone D %s %s %s", aUserFileType, MAPI.GET_FILE_LENGTH(fileName), fileName));
                MAPI.SET_FILE_DONE(fileName);
                return fileName;
            }
        }
        return fileName;
    }

    public static synchronized String modifyUseInfo(BAppUser bAppUser) {
        if (changeUser()) {
            clearMyManage();
            int areaCode = 0xffff;
            if (bAppUser.Province != null && bAppUser.City != null){
                areaCode = mMyUtils.getAreaRankData(String.format("%s %s", bAppUser.Province, bAppUser.City));
            }else if (bAppUser.City != null){
                areaCode = mMyUtils.getAreaRankData(String.format("%s", bAppUser.City));
            }else if (bAppUser.Province != null){
                areaCode = mMyUtils.getAreaRankData(String.format("%s", bAppUser.Province));
            }
//            int areaCode = mMyUtils.getAreaRankData(String.format("%s %s", bAppUser.Province, bAppUser.City));
            MLOG(String.format("UserInfoA methodTypeA %04x %s %s", areaCode, bAppUser.Province, bAppUser.City));
            SubUtils subUtils = new SubUtils();
            int birthday = subUtils.BIRTHDAY_STRING_DEC(bAppUser.Birthday);
            CApiUtils cApiUtils = new CApiUtils();
            String modiftText = String.format("%02x=%s,%02x=%x,%02x=%x,%02x=%x,%02x=%s,",
                    KCB_MODIFY_USER_NAME, cApiUtils.encodeRichText(bAppUser.UserName),
                    KCB_MODIFY_USER_GENDER, bAppUser.Gender,
                    KCB_MODIFY_USER_BIRTHDAY, birthday,
                    KCB_MODIFY_USER_AREA, areaCode,
                    KCB_MODIFY_USER_INTRO, cApiUtils.encodeRichText(bAppUser.Intro));
            MLOG(String.format("UserInfoA modifyUseInfo %s %s", gUserID, modiftText));
            mMyManage.mSvrManage.modifyUserDetail(gUserID, modiftText, true);
            long tick = System.currentTimeMillis();
            while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
                int methodType = mMyManage.mSvrManage.getMethodType();
//                MLOG(String.format("methodTypeA %08x %s %s", methodType, bAppUser.UserName, modiftText));
                if ((methodType & tTypeMask) == MANAGE_MODIFY_DETAIL) {
                    String message = mMyManage.mSvrManage.getMethodMessage(methodType);
                    if (message != null) {
                        if ("ok".equals(message)) {
                        }
                        return message;
                    }
                }
                sleepWaitting(100);
            }
            MLOG(String.format("methodTypeA44"));
            return "超时，请重试...";
        } else {
            return "更换ID不成功";
        }

    }
    public static synchronized String uploadPhotoFile(String fileName, AUserFileType aUserFileType) {
        if (changeUser()) {
            ByteBuffer mRunState = ByteBuffer.allocateDirect(128);
            int type = ARoomType.ROOM_USER.getType() << 6;
            MLOG(String.format("UserInfoA uploadPhotoFile B %s %s %s %s %s", type, aUserFileType.getType(), gUserID, gLoginFlag, fileName));
            return mMyUtils.threadUploadFiles(type, gUserID, aUserFileType.getType(), 0, 0, "", fileName, mRunState);
        }
        return "超时";
    }
    public static synchronized AFileInfo getAFileInfo(AFileBase aFileBase, long tick) {
        String worksName = null;
        String artistName = null;
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            ABean aBean = MAPI.mMyWorks.fetchFileDetail(aFileBase, null);
            if (worksName == null) {
                worksName = mMyUtils.getFileName(aFileBase);
            }
            if (artistName == null) {
                artistName = mMyUtils.getFileSubName(aFileBase);
            }
            if (aBean.ErrorStr == null && aBean.mObject instanceof AFileInfo && worksName != null && artistName != null) {
                return (AFileInfo)aBean.mObject;
            }
            sleepWaitting(100);
        }
        return null;
    }
    public static synchronized AFileInfo[] searchWorks(AUserSearchType aUserSearchType, String text) {
        mMyWorks.findInSvr(AFetchType.LIST_DELETE, aUserSearchType, text, null, 0);  // 先清除上次的结果
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 15000) {
            ABean aBean = mMyWorks.findInSvr(AFetchType.LIST_NORMAL, aUserSearchType, text, null, 0);  // gSearchStep的数字表示  0歌手列表 1普通伴奏 2合唱伴奏 3K歌作品  // 0名人列表 1朗诵伴奏 2朗诵合唱 3朗诵作品
            if (aBean.ErrorStr == null) {
                int length = (aBean.mBean != null) ? aBean.mBean.size() : 0;
                if (length > 0) {
                    AFileInfo[] aFileInfos = new AFileInfo[length];
                    for (int index = 0; index < length; index++) {
                        aFileInfos[index] = getAFileInfo((AFileBase) aBean.mBean.get(index), tick);
                    }
                    return aFileInfos;
                }
                break;
            }
        }
        return null;
    }
    public static synchronized String[] searchUser(String text) {
        mMyWorks.findInSvr(AFetchType.LIST_REFRESH, AUserSearchType.LIST_SEARCH_KCID, text, null, 0);  // 先清除上次的结果
        SubUtils subUtils = new SubUtils();
        int mode = subUtils.checkTextMode(text);       // 检查帐号是邮件或者手机或者都是ASCII 返回0=DEC32 数字  1=手机  2=邮件 3=不全是数字  4=不全是ASCII
        int varType = (mode == 0) ? AVarType.VAR_KCID.getType() : AVarType.VAR_USER_NAME.getType();
        int userID = 0;
        boolean isAccurate = false;
        int gender = -1;
        int area = -1;
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 15000) {
            ABean aBean = mMyWorks.findInSvr(AFetchType.LIST_NORMAL, AUserSearchType.LIST_SEARCH_KCID, text, varType, userID, isAccurate, gender, area, null, 0);  // gSearchStep的数字表示  0歌手列表 1普通伴奏 2合唱伴奏 3K歌作品  // 0名人列表 1朗诵伴奏 2朗诵合唱 3朗诵作品
//                    MLOG(String.format("searchUserA %s(%s)%s(%s)", aBean.ErrorStr, text, varType, userID));
//                findInSvr(AFetchType aFetchType, AUserSearchType aUserSearchType, String text, int varType, int userID, boolean isAccurate, int gender, int area, List<ALoadBean > lists, int fetchCount)
            if (aBean.ErrorStr == null) {
                int length = (aBean.mBean != null) ? aBean.mBean.size() : 0;
                if (length > 0) {
                    String[] strings = new String[length];
                    for (int index = 0; index < length; index++) {
                        strings[index] = String.format("%s", ((AUserBase) aBean.mBean.get(index)).UserID);
                    }
                    return strings;
                }
                break;
            }
        }
        return null;
    }
    public static synchronized String[] getUserRelation(AUserRelationType aUserRelationType, String userIdS){
        AUserBase aUserBase = new AUserBase();
        aUserBase.UserID = MAPI.STRING_DEC32(userIdS);
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 15000) {
            ABean aBean = mMyManage.fetchUserRelationsList(AFetchType.LIST_NORMAL, aUserRelationType, aUserBase, null, 0);
            if (aBean.ErrorStr == null) {
                int length = (aBean.mBean != null) ? aBean.mBean.size() : 0;
//                    if (length > 0) {
//                        AFileInfo[] aFileInfos = new AFileInfo[length];
//                        for (int index = 0; index < length; index++) {
//                            aFileInfos[index] = getAFileInfo((AFileBase) aBean.mBean.get(index), tick);
//                        }
//                        return aFileInfos;
//                    }
                break;
            }
        }
        return null;

    }

    public static synchronized String writeKgAppDbs(String text){
        MLOG(String.format("KgAppDbsA writeKgAppDbs A %s", text));
        if (changeUser()) {
            MLOG(String.format("KgAppDbsA writeKgAppDbs B %s", text));
            return mMyTools.writeKgAppDbs(text.getBytes().length, text.getBytes());
        }
        MLOGE(String.format("KgAppDbsA writeKgAppDbs Error %s", text));
        return mMyUtils.getLastError();
    }
    public static synchronized String readKgAppDbs(String text){
        if (changeUser()) {
            return mMyTools.readKgAppDbs(text.getBytes().length, text.getBytes());
        }
        MLOGE(String.format("KgAppDbsA readKgAppDbs Error %s", text));
        return null;
    }
    private static synchronized String waitMyWorksDone(int type){
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 9000 && !IsPause) {
            int methodType = mMyWorks.mSvrWorks.getMethodType();
//            MLOG(String.format("setCommentA1 %08x", methodType));
            if (type == 0) {
                if (mMyWorks.isSuccessOperationWorks(methodType)) {
//                    MLOG(String.format("addLikeWorks A2 %s %08x", gUserID, methodType));
                    return mMyWorks.mSvrWorks.getMethodMessage(methodType);
                }
            }else if (type == 1) {
                MLOG(String.format("sendGifts A3a %08x", methodType));
//                if (mMyWorks.isSuccessSendGift(methodType)) {
//                    MLOG(String.format("sendGifts A3b %08x", methodType));
//                    return mMyWorks.mSvrWorks.getMethodMessage(methodType);
//                }

            }
            if ((methodType & 0xf0000000) != 0){
                MLOG(String.format("addLikeWorks A5 %08x", methodType));
                mMyWorks.mSvrWorks.getMethodMessage(methodType);
            }
            sleepWaitting(100);
        }
        return "超时";
    }
    private static synchronized String waitMyManageDone(int type){
        long tick = System.currentTimeMillis();
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            int methodType = mMyManage.mSvrManage.getMethodType();
//            MLOG(String.format("addCareUserA1 %s %08x", type, methodType));
            if (type == 0) {
                if (mMyManage.isSuccessSetUserRelations(methodType)) {
                    MLOG(String.format("addCareUserA2 %08x", methodType));
                    return mMyManage.mSvrManage.getMethodMessage(methodType);
                }
            }else if (type == 1) {
                if (mMyManage.isSuccessOperationMoney(methodType)) {
                    MLOG(String.format("addCareUserA8 %08x", methodType));
                    return mMyManage.mSvrManage.getMethodMessage(methodType);
                }
            }
            if ((methodType & 0xf0000000) != 0){
                MLOG(String.format("addCareUserA3 %08x", methodType));
                mMyManage.mSvrManage.getMethodMessage(methodType);
            }
            sleepWaitting(100);
        }
        return "超时";
    }


    public static synchronized boolean getGiftAndRank(List<AFileBase> giftIcon, List<AFileBase> rankArea){
        if (changeUser()){
            if (giftIcon != null){
                AUserBase aUserBase = mMyUtils.getSpecAccount(AAccountType.ID_GIFT_ICON);
                long tick = System.currentTimeMillis();
                while ((System.currentTimeMillis() - tick) < 9000) {
                    ABean aBean = mMyWorks.fetchWorksList(AFetchType.LIST_NORMAL, AWorksType.WORKS_TYPE_PHOTO, TOOLS_WORKS_LIST_WORKS, aUserBase, null, 0);
//                            MLOG(String.format("QueueA getGiftAndRank A %s", aBean.ErrorStr));
                    if (aBean.ErrorStr == null && aBean.mBean != null){
                        int length = aBean.mBean.size();
//                                MLOG(String.format("QueueA getGiftAndRank B %s", length));
                        for (int index = 0; index < length; index++) {
                            AFileBase aFileBase = (AFileBase)aBean.mBean.get(index);
                            mMyUtils.getFileName(aFileBase);    // 礼物名称
                            giftIcon.add(aFileBase);
                        }
//                                MLOG(String.format("QueueA ID_GIFT_ICON %08x", giftIcon.size()));
                        getRankAreaData(rankArea);
                        return true;
                    }
                    sleepWaitting(100);
                }
                return false;
            }
            getRankAreaData(rankArea);
            return true;
        }
        return false;
    }
    private static synchronized boolean getRankAreaData(List<AFileBase> rankArea) {
//        MLOG(String.format("QueueA getRankAreaData A %08x", rankArea.size()));
        if (rankArea != null) {
            long tick = System.currentTimeMillis();
            while ((System.currentTimeMillis() - tick) < 9000) {
                AUserBase aUserBase = mMyUtils.getSpecAccount(AAccountType.ID_AREA_DATA);
                ABean aBean = mMyWorks.fetchWorksList(AFetchType.LIST_NORMAL, AWorksType.WORKS_OTHER, wpapper.TOOLS_WORKS_LIST_WORKS, aUserBase, null, 0);
                if (aBean.ErrorStr == null && aBean.mBean != null) {
                    rankArea.addAll((List) aBean.mBean);
                    return true;
                }
                sleepWaitting(100);
            }
            return false;
        }
        return true;
    }


    public static synchronized boolean changeUser(){
        long tick = System.currentTimeMillis();
        if (gUserID == mMyUtils.getCurrentUserID()) {           // 当前的用户相同
//            MLOG(String.format("changeUser A %s(%s)%s(%s)", mMyUtils.getCurrentUserID(), gUserID, mMyUtils.getCurrentLoginUserID(), LoginFlag));
            return true;
        }
        mMyManage.loginSvr(gLoginFlag, "", "");
        MLOG(String.format("UserInfoA changeUser KgAppDbsA AA %s", gLoginFlag));
        while ((System.currentTimeMillis() - tick) < 5000 && !IsPause) {
            int currentLoginUserID = mMyUtils.getCurrentLoginUserID();
            if (currentLoginUserID != 0) {
                if (gUserID == currentLoginUserID && gUserID == mMyUtils.getCurrentUserID()) {
//                            MLOG(String.format("changeUser KgAppDbsA B %s(%s)%s(%s)", mMyUtils.getCurrentUserID(), gUserID, mMyUtils.getCurrentLoginUserID(), LoginFlag));
                    return true;
                }else {
                    break;
                }
            }
//                    MLOG(String.format("changeUser E %s(%s)%s(%s)", mMyUtils.getCurrentUserID(), gUserID, mMyUtils.getCurrentLoginUserID(), LoginFlag));
            sleepWaitting(1000);
        }
        gLastError = mMyUtils.getLastError();
        MLOGE(String.format("UserInfoA changeUser KgAppDbsA Error %s -> %s(%s) %s(%s)%sms", mMyUtils.getCurrentUserID(), gUserID, mMyUtils.getCurrentLoginUserID(), mMyUtils.getLastError(), gLoginFlag, System.currentTimeMillis() - tick));
        return false;
    }
    private static synchronized void clearMyWorks(){
        while (true) {
            int methodType = mMyWorks.mSvrWorks.getMethodType();
            if (methodType == 0){
                break;
            }
            mMyWorks.mSvrWorks.getMethodMessage(methodType);
        }
    }
    private static synchronized void clearMyManage(){
        while (true) {
            int methodType = mMyManage.mSvrManage.getMethodType();
            if (methodType == 0){
                break;
            }
            mMyManage.mSvrManage.getMethodMessage(methodType);
        }
    }


    private static void breakWaitting(){                           // 退出任何等待
        if (gLoginFlag != null) {
            if (gLoginFlag != null) {
                synchronized (gLoginFlag) {                             // 借用对象锁
                    gLoginFlag.notifyAll();
                }
            }
        }
    }
    private static void sleepWaitting(int millisecond){            // 等待毫秒
        if (gLoginFlag != null) {
            synchronized (gLoginFlag) {                                 // 借用对象锁
                try {
                    gLoginFlag.wait(millisecond);                       // 等待信号
                } catch (Exception e) {
                }
            }
        }else {
            MSLEEP(millisecond);
        }
    }

}
